package de.ama.view;

import de.ama.crawler.Entry;
import de.ama.crawler.Store;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;

public class SelectPanel extends JPanel implements ClickHandler{
    private Box mainBox = Box.createVerticalBox();
    private JTextField searchInput = new JTextField();
    private EntryTableView table = new EntryTableView();
    private Dialog dlg;


    public SelectPanel(Dialog dlg) {
        this.dlg = dlg;
        dlg.initComponent(this);
        dlg.initComponent(mainBox);
        dlg.initComponent(searchInput);
        dlg.initComponent(table);

        searchInput.setPreferredSize(new Dimension(900, 20));
        table.setPreferredSize(new Dimension(900, 700));

        mainBox.add(table);
        mainBox.add(Box.createVerticalStrut(10));
        mainBox.add(searchInput);
        add(mainBox);

        initKeyListeners();

        table.setClickHandler(this);
    }

    private void initKeyListeners() {
        searchInput.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                dlg.searchAgain(searchInput.getText());
            }
        });

        mainBox.registerKeyboardAction(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                dlg.onCancel();
            }
        }, KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
    }


    public void showData(Entry entry) {
        searchInput.setText(entry.getPath());
        table.setModel(new EntryTableModel(entry.getMatches(), 6));
        dlg.validate();
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                searchInput.requestFocus();
            }
        });
    }

    public void onClick(Entry e, MouseEvent me) {
        Store.get().replaceMovie(dlg.getEntry(),e);
        dlg.onCancel();
    }
}
